package com.zsr.config;

import com.zsr.pojo.User;
import com.zsr.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

/**
 * @Author zsr
 * @Desc
 * @Date 2021/5/25 11:28
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired @Qualifier("userServiceImpl")
    UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //info.addStringPermission("user:add");

        //拿到登录的这个对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User)subject.getPrincipal();

        //设置当前用户的权限
        info.addStringPermission(currentUser.getPerms());
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了认证");
        //用户名 密码  数据库中取

        //String name ="root";
        //String password="123456";

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        //连接真实的数据库
        //数据库需要username唯一
        User user = userService.queryUserByName(token.getUsername());

        if(user==null){
            return null;//抛出异常 UnknownAccountException
        }
        //可以加密：  md5  md5盐
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
        /*if(!token.getUsername().equals(name)){
            return null;//抛出异常 UnknownAccountException
        }
        return new SimpleAuthenticationInfo("",password,"");*/
    }
}
